﻿using log4net;
using SuperFx;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;

namespace SuperMoney.AdPlatformCallback.Controllers
{
	public class WapxController : Controller
	{
		const string adPlatform = "wapx";

		//
		// GET: /Wapx/Android

		public ActionResult Android(string adv_id, string app_id, string key, string udid, int? bill, int? points)
		{
			string[] ips = ConfigurationManager.AppSettings["WapxIPS"].Replace(" ", "").Split(',');

			string ip = this.Request.ServerVariables.Get("REMOTE_ADDR");
			if (!ips.Contains(ip))
			{
				LogManager.GetLogger("Android-Wapx").Error(ip + "IP地址不合法");
				return Content("IP不地址合法");
			}

			if (String.IsNullOrWhiteSpace(adv_id) || String.IsNullOrWhiteSpace(app_id))
			{
				LogManager.GetLogger("Android-Wapx").Error("参数为空不合法");
				return Content("参数为空不合法");
			}

			string orderId = Md5Hash.Compute(adv_id + app_id + udid);
			try
			{
				if (!bill.HasValue) bill = 0;
				if (!points.HasValue) points = 0;
				AdRecordService.Instance.Create(adPlatform, orderId, null, 0, udid, adv_id, null, null, points.Value, bill.Value / 100m, app_id, "Android", key);
			}
			catch (Exception<AdRecordExistsExceptionArgs> ex)
			{
				LogManager.GetLogger("Android-Wapx").Error(orderId + "万普广告记录已存在", ex);
				HttpContext.Response.StatusCode = 403;
			}
			catch (Exception ex)
			{
				LogManager.GetLogger("Android-Wapx").Error(orderId + "服务器端错误", ex);
				HttpContext.Response.StatusCode = 500;
			}
			return new EmptyResult();
		}

		//
		// GET: /Wapx/iOS

		public ActionResult iOS(string adv_id, string app_id, string key, string udid, int? bill, int? points)
		{
			string[] ips = ConfigurationManager.AppSettings["WapxIPS"].Replace(" ", "").Split(',');

			string ip = this.Request.ServerVariables.Get("REMOTE_ADDR");
			if (!ips.Contains(ip))
			{
				LogManager.GetLogger("iOS-Wapx").Error(ip + "IP地址不合法");
				return Content("IP不地址合法");
			}

			if (String.IsNullOrWhiteSpace(adv_id) || String.IsNullOrWhiteSpace(app_id))
			{
				LogManager.GetLogger("iOS-Wapx").Error("参数为空不合法");
				return Content("参数为空不合法");
			}

			string orderId = Md5Hash.Compute(adv_id + app_id + udid);
			try
			{
				if (!bill.HasValue) bill = 0;
				if (!points.HasValue) points = 0;
				AdRecordService.Instance.Create(adPlatform, orderId, null, 0, udid, adv_id, null, null, points.Value, bill.Value / 100m, app_id, "iOS", key);
			}
			catch (Exception<AdRecordExistsExceptionArgs> ex)
			{
				LogManager.GetLogger("iOS-Wapx").Error(orderId + "万普广告记录已存在", ex);
				HttpContext.Response.StatusCode = 403;
			}
			catch (Exception ex)
			{
				LogManager.GetLogger("iOS-Wapx").Error(orderId + "服务器端错误", ex);
				HttpContext.Response.StatusCode = 500;
			}
			return new EmptyResult();
		}

	}
}
